// 设置默认信息
$.validator.setDefaults({
    submitHandler: function (val) {
        //submit('',successcallback('修改成功,请重新登陆',$('.formsub').attr('tipurl')));
    },
    groups: {
        date: "year month day"
    },
    errorPlacement: function (error, element) {
        element.parents('td').append(error);
        element.parents('.l_b').append(error);
        element.parents('.l_b').find('.prompt').hide();
        element.parent('td').find('.custom-combobox').addClass('error');
    }
});

$(document).ready(function () {
    var myThis = $("#combobox");
    $(".combobox_b a").hide();
    var start_apply = $(".start_apply");
    function combobox() {
        $('#combobox').autocomplete({
            source: function (request, response) {
                //alert(request.term);
                $.ajax({
                    url: $("#selcompany").val(),
                    data: {
                        keyword: request.term
                    },
                    dataType: 'json',
                    type: 'POST',
                    minLength: 0,
                    success: function (data) {

                        if (data.length == 0) {
                            $(".combobox_b a").hide();

                            // myThis.tooltip({
                            //     position: {my: "left+10 top-80", at: "left top"}
                            // })
                            //         .on('mouseout change focusout', function (event) {
                            //             event.stopImmediatePropagation();
                            //         });

                            // myThis.prop("title", "未匹配到相关企业，请检查是否输错，" +
                            //         "如有疑问，请联系客服400-800-900");
                            // myThis.tooltip("open");
                            // setTimeout(function () {
                            //     myThis.tooltip('close');
                            //     myThis.prop("title", "");
                            // }, 2500)
                        } else {
                            response(data);
                            $(".combobox_b a").show();
                            //  myThis.tooltip("close");                     
                        }
                    }
                });
            },
            focus: function (event, ui) {
                if (ui.item.value == '-1') {
                    $("#combobox").val('');
                } else {
                    $("#combobox").val(ui.item.label);
//                $("#companyname").val(ui.item.value);
                    $(".com_name").text(ui.item.label);
                    $("#payeeid").val(ui.item.value);
                    return false;
                }
                $(".combobox_b a").hide();
            },
            select: function (event, ui) {
                if (ui.item.value == '-1') {
                    $("#combobox").val('');
                } else {
                    $("#combobox").val(ui.item.label);
                    $("#payeeid").val(ui.item.value);
//                $("#companyname").val(ui.item.value);
                    $(".com_name").text(ui.item.label);

                }
                $(".combobox_b a").hide();
                event.preventDefault();
            }

        });
    }
    combobox();


    // 限制只能输入数字
    var record;
    // $("#bank_account,.paid_split input").on('keyup',function(){
    start_apply.on('keyup', '.line_num,.bank_num', function (event) {
        var myThis = $(this);
        var val = myThis.val();
        var decimalReg = /^[1-9][0-9]*$/;
        if (val != '' && decimalReg.test(val)) {
            record = val;
        } else {
            if (val != '') {
                myThis.val(record);
            }
        }
        myThis.blur(function () {
            record = '';
        });
    })

    start_apply.on('keyup', '.loan_account input', function (event) {
        var myThis = $(this);
        var val = myThis.val();
        var decimalReg =  /^\d{0,999}\.{0,1}(\d{1,999})?$/;
        if (val != '' && decimalReg.test(val)) {
            record = val;
        } else {
            if (val != '') {
                myThis.val(record);
            }
        }
        myThis.blur(function () {
            record = '';
        });
    })

    start_apply.on('focus', '.table_box input[type=text]', function (event) {
        $(this).addClass('u-ipt-active');
        $(this).removeClass('error');
        $(this).next('label.error').hide();
        $(this).parent('.l_b').find('label.error').hide();
        $(this).parent('.l_b').find('.prompt').show();
    });


    start_apply.on('blur', '.table_box input[type=text]', function (event) {
        $(this).removeClass('u-ipt-active');
        $("#start_apply").validate().element($(this))
        if ($(this).parent().find('label.error').is(":visible")) {
            $(this).addClass('error');
            $(this).parent('.l_b').find('.prompt').hide();
        } else {
            $(this).removeClass('error');
            $(this).removeClass('u-ipt-active');
            $(this).parent('.l_b').find('.prompt').show();
        }
    });


    // 单独选择更换背景
    start_apply.on('click', '.check_bg input', function (event) {
        if (this.checked) {
            $(this).prop('checked', true);
            $(this).parent('.check_bg').addClass('check_active');

        } else {
            $(this).prop('checked', false);
            $(this).parent('.check_bg').removeClass('check_active');
        }
    })

    // 上传文件
    var
            $list = $('#thelist'),
            // $btn = $('#ctlBtn'),
            state = 'pending',
            fileCount = 0,
            uploader,
            truefilename;

    var uploader = WebUploader.create({
        // swf文件路径
        swf: 'Uploader.swf',

        // 文件接收服务端。
        server: $('#uploadcontract').val(),

        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建，可能是input元素，也可能是flash.
        pick: '#picker',
        chunked: true,
        chunkSize: 2 * 1024 * 1024,
        multiple: false,
        //fileNumLimit: 1,
        accept: {
            title: 'PDF文件',
            extensions: 'pdf',
            mimeTypes: '.pdf'
        }
    });

    uploader.addFile = function (file) {
        if ($('.org').length > 0)
        {
            $("#thelist .item").remove();
        }
        $('#fileurl').val('');
        $('#filename').val('');
        var $li = $(
                '<div id="' + file.id + '" class="item fn-clear">' +
                '<h4 class="info">' + file.name + '</h4>' +
                '<i class="delete"></i>' +
                '</div>');
        if (fileCount > 1) {
            $("#thelist .item").remove();
            uploader.removeFile(file, true);
            $li.appendTo($list);
        } else {
            $li.appendTo($list);
        }
        truefilename = file.name;
        // $li.appendTo($list);
        filename = file.name;
        var index1 = filename.lastIndexOf(".");
        var index2 = filename.length;
        var ext = filename.substring(index1, index2);//后缀名
        file.name = WebUploader.guid() + ext;
        $li.on('click', '.delete', function () {
            uploader.removeFile(file, true);
        })
    };

    $(".delete").click(function () {
        $('#fileurl').val('');
        $('#filename').val('');
        $(this).parents('.item').remove();
    })

    start_apply.on('click', '.split_delete', function (event) {
        $(this).parent('.split_child').remove();
    });

    uploader.onFileQueued = function (file) {

        fileCount++;
        uploader.addFile(file);
    };

    uploader.onFileDequeued = function (file) {
        fileCount--;
        removeFile(file);
    };

    $list.on('mouseenter mouseleave', '.item', function () {
        $(this).toggleClass("hover");
    });

    //删除文件
    function removeFile(file) {

        var $li = $('#' + file.id);
        $li.remove();
    }

    uploader.on('uploadError', function (file) {
        var $li = $('#' + file.id),
                $error = $li.find('div.error');

        // 避免重复创建
        if (!$error.length) {
            $error = $('<div class="error"></div>').appendTo($li);
        }

        $error.text('上传失败');

    });

    $('#picker').change(function () {
        // $(this).parents('td').find("label.error").hide();
        //account_form.form();
        if ($("#thelist .item").length > 0) {
            $(this).parents('td').find("label.error").hide();
        }
    })


    uploader.on('uploadSuccess', function (file, response) {
        if (response.error.code == '0')
        {

            $('#fileurl').val(response.result.showpath);
            $('#filename').val(truefilename);
            oktipsoption = {
                type: 1,
                url: $('.formsub').attr('url'),
                msg: '提交成功'
            };
            ajaxform.init(oktipsoption, '.formsub');
            ajaxform.submit();
        } else
        {
            layer.alert('文件上传失败', {
                icon: 2,
                btn: false,
                closeBtn: 0,
                time: 2000
            });
        }
    });

    uploader.on('uploadError', function (file) {
        layer.alert('文件上传失败', {
            icon: 2,
            btn: false,
            closeBtn: 0,
            time: 2000
        });
    });

    $("#upload_btn").click(function () {
        if (account_form.form()) {

            if ($('#fileurl').val() !== '')
            {
                oktipsoption = {
                    type: 1,
                    url: $('.formsub').attr('url'),
                    msg: '提交成功'
                };
                ajaxform.init(oktipsoption, '.formsub');
                ajaxform.submit();
            } else
            {
                uploader.upload();
            }
        }


    });

    //验证填写用款金额与可用额度的比较

    $.validator.addMethod("chkmoney", function (value) {
        var tt = $(".available span").text().replace(/,/g, "");
        if (parseInt($("#money").val()) <= parseInt(tt)) {
            return true
        }
    });

    $.validator.addMethod("chkbankname", function (value) {
        var yzcodeReg = /^[\u4e00-\u9fa5]+$/;
        return yzcodeReg.test(value);
    });

    var account_form = $("#start_apply").validate({
        rules: {
            company_name: {
                required: true
            },
            file: {
                required: {
                    depends: function () {
                        return ($("#thelist .item").length <= 0);
                    }
                }
            },
            quota: {
                required: true,
                chkmoney: true
            },
            line_num: {
                required: true
            },
            bank_num: {
                required: true,
                minlength: 16
            },
            address: {
                required: true
            },
            bank_name: {
                required: true,
                chkbankname: true
            },
            payee: {
                required: true
            }
        },
        messages: {
            company_name: {
                required: '请输入供应商上游企业'
            },
            file: {
                required: '请上传合同'
            },
            quota: {
                required: '请填写用款金额',
                chkmoney: '用款金额不能大于可用额度'
            },
            line_num: {
                required: '请填写联行号'
            },
            bank_num: {
                required: '请填写收款银行账号',
                minlength: '银行卡号至少为16位'
            },
            address: {
                required: '请填写收款人地址 '
            },
            bank_name: {
                required: '请填写开户行名称 ',
                chkbankname: '开户行名称为中文'
            },
            payee: {
                required: '请填写收款人的姓名'
            }
        },
        focusInvalid: false,
        onkeyup: false
    });
})